package cn.edu.nju.software.cdiy.action.user.all;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.cdiy.bean.Hardware;
import cn.edu.nju.software.cdiy.service.Service;
import cn.edu.nju.software.cdiy.util.Constant;
import cn.edu.nju.software.cdiy.util.Item;
import cn.edu.nju.software.cdiy.util.SortType;
import cn.edu.nju.software.cdiy.util.SortWay;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("serial")
public class HardwareSearchAction<T extends Hardware> extends ActionSupport implements SessionAware, ServletRequestAware, Preparable {

	private static String S_FILTER;
	private static String S_RESULT;
	private static String S_QUERY_STRING;
	private static String S_PAGE_NUM;
	private static String S_RESULT_AMOUNT;
	private Map<String, Object> session;
	private HttpServletRequest request;
	private Service<T> service;
	private Map<String,List<Integer>> selectedConditions;
	private int sortOrder = Constant.TIME;
	private int pageNum = 1;
	
	public static void setSessionKey(String filter, String result, String queryString, String pageNum, String resultAmount) {
		S_FILTER = filter;
		S_RESULT = result;
		S_QUERY_STRING = queryString;
		S_PAGE_NUM = pageNum;
		S_RESULT_AMOUNT = resultAmount;
	}
	
	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setService(Service<T> service) {
		this.service = service;
	}

	public Map<String, List<Integer>> getSelectedConditions() {
		return selectedConditions;
	}

	public void setSelectedConditions(Map<String, List<Integer>> selectedConditions) {
		this.selectedConditions = selectedConditions;
	}

	public int getSortOrder() {
		return sortOrder;
	}

	public void setSortOrder(int sortOrder) {
		this.sortOrder = sortOrder;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	@Override
	public void prepare() throws Exception {
		Map<String, String[]> parametersMap = request.getParameterMap();
		if (selectedConditions != null) {
			selectedConditions.clear();
		}
		for (String parameterName : parametersMap.keySet()) {
			String parameterValue = parametersMap.get(parameterName)[0];
			//System.out.println(parameterName + ": " + parameterValue);
			/*如果符合map[name]=1,2的格式就对selectedConditions进行填充*/
			if (parameterName.matches("^\\w+\\[\\w+\\]$") && parameterValue.matches("^\\d+(,\\d+)*$")) {
				if (selectedConditions == null) {
					selectedConditions = new HashMap<String, List<Integer>>();
				}
				String key = parameterName.substring(parameterName.indexOf('[')+1, parameterName.length()-1);
				List<Integer> valueList = new LinkedList<Integer>();
				for (String value : parameterValue.split(",")) {
					valueList.add(Integer.parseInt(value));
				}
				selectedConditions.put(key, valueList);
			}
		}
	}

	@Override
	public String execute() throws Exception {
		/*System.out.println("---===SearchHardware.execute()===---");
		if (selectedConditions == null) {
			System.out.println("selectedConditions is null!");
		} else {
			System.out.println("selectedConditions.size(): "+selectedConditions.size());
			for (String key : selectedConditions.keySet()) {
				System.out.println(key+": "+selectedConditions.get(key));
			}
		}*/
		if(!session.containsKey(S_FILTER)) {
			Map<String,List<Item>> filter = service.getFilterBoard();
			session.put(S_FILTER, filter);
		}
		
		String sessionQueryString = (String) session.get(S_QUERY_STRING);
		String queryString = request.getQueryString();
		if (queryString == null) {
			queryString = "sortOrder=1&pageNum=1";
			sortOrder = Constant.TIME;
			pageNum = 1;
		}
		boolean sameCondition = false;
		boolean samePageWindow = false;
		if (sessionQueryString != null) {
			//判断查询条件和排序方式是否相同
			sameCondition = sessionQueryString.split("pageNum=")[0].equals(queryString.split("pageNum=")[0]);
			//判断翻页前后页数是否在同一个页面缓存窗口（比如10页）
			Integer sessionPageNum = (Integer) session.get(S_PAGE_NUM);
			samePageWindow = sessionPageNum!=null && (sessionPageNum-1)/Constant.PAGE_RETURN==(pageNum-1)/Constant.PAGE_RETURN;
		}
		session.put(S_QUERY_STRING, queryString);
		session.put(S_PAGE_NUM, pageNum);
		
		if (!sameCondition || !samePageWindow) {
			if (!sameCondition) {
				session.put(S_RESULT_AMOUNT, service.getFilterResultLength(selectedConditions, null));
			}
			List<T> result = null;
			switch (sortOrder) {
			case Constant.TIME:
				result = service.filter(pageNum, selectedConditions, SortType.NEW, SortWay.DESC, null);
				break;
			case Constant.SALE:
				result = service.filter(pageNum, selectedConditions, SortType.HOT, SortWay.DESC, null);
				break;
			case Constant.PRICE_LOW:
				result = service.filter(pageNum, selectedConditions, SortType.PRICE, SortWay.ASC, null);
				break;
			case Constant.PRICE_HIGH:
				result = service.filter(pageNum, selectedConditions, SortType.PRICE, SortWay.DESC, null);
				break;
			case Constant.SCORE_USER:
				result = service.filter(pageNum, selectedConditions, SortType.W_SCORE, SortWay.DESC, null);
				break;
			case Constant.SCORE_PRO:
				result = service.filter(pageNum, selectedConditions, SortType.Z_SCORE, SortWay.DESC, null);
				break;
			//Constant.PERFORMANCE
			default:
				result = service.filter(pageNum, selectedConditions, SortType.PERFORMANCE, SortWay.DESC, null);
				break;
			}
			session.put(S_RESULT, result);
		}
		
		return SUCCESS;
	}
	
}
